package framework.view;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;

import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

import framework.gui.*;
import framework.controller.*;
import framework.model.*;

public class LoginView extends InteractiveView {
	
	// Components
	private JLabel serverLabel;
	private JLabel nameLabel;
	private JTextField serverField;
	private JTextField nameField;
	private JButton loginButton;
	
	/**
	 * Constructor without parameters
	 * @method LoginView (Constructor)
	 * @param <LoginModel> model
	 * @param <LoginController> controller
	 */
	public LoginView(LoginModel model, LoginController controller) {
		super(model, controller);
		this.init();
		this.addPanels();
	}

	/**
	 * Add several panels to the loginView
	 * @method addPanels
	 */
	private void addPanels() {
		super.add(this.nameLabel);
		super.add(this.nameField);
		super.add(this.serverLabel);
		super.add(this.serverField);
		super.add(new JLabel(""));
		super.add(this.loginButton);
	};
	
	private void init() {
		// Panel
		GridLayout gridLayout = new GridLayout(0, 2);
		gridLayout.setVgap(10);
		gridLayout.setHgap(10);
		this.setLayout(gridLayout);
		this.setBorder(new EmptyBorder(10, 10, 10, 10));
		// Textfields
		this.nameField 	 = new JTextField();
		this.serverField = new JTextField();
		// Labels
		this.nameLabel 	 = new JLabel("username: ");
		this.serverLabel = new JLabel("server: ");
		// Buttons
		this.loginButton = new JButton("login");
		this.loginButton.setActionCommand("login");
		this.loginButton.addActionListener(this);
		//TextField values
		this.nameField.setText("Jaap");
		this.serverField.setText("127.0.0.1:7777");
	}
	
	@Override
	public LoginModel getModel() {
		return (LoginModel)super.getModel();
	};
	
	@Override
	public LoginController getController() {
		return (LoginController)super.getController();
	};

	@Override
	public void actionPerformed(ActionEvent e) {
		switch(e.getActionCommand()) {
			case "login" :
				//Handle login form request
				this.getController().handleLoginRequest(this.nameField.getText(), this.serverField.getText());
			break;
			case "login_updated" :
				if(this.getModel().isLoggedIn()) {
					SwingUtilities.getWindowAncestor(this).dispose();
					this.getController().handleLobbyRequest();
				}
			break;
		};
	}

}
